/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DeviceGroupDetailView.java
 *
 * Created on 02.Şub.2010, 17:57:57
 */
package org.testis.gui.mvc.view.testbed;

import org.testis.gui.mvc.controller.TestBedControllerList;
import org.testis.gui.mvc.controller.testbed.DeviceGroupDetailController;
import org.testis.gui.mvc.utilities.AtofValidationUtils;
import org.testis.gui.mvc.utilities.Validatable;
import org.testis.gui.mvc.utilities.ValidationUtils;
import org.testis.gui.mvc.view.AbstractViewPanel;
import org.testis.gui.mvc.view.AtofBaseDialog;
import org.testis.orm.testbed.refined.DeviceGroupDetailRefined;
import org.testis.orm.testbed.refined.DeviceGroupFactory;
import org.testis.orm.testbed.refined.DeviceGroupRefined;
import org.testis.orm.testbed.refined.OperatingSystemFactory;
import org.testis.orm.testbed.refined.OperatingSystemRefined;
import org.testis.orm.testbed.refined.TestPcFactory;
import org.testis.orm.testbed.refined.TestPcRefined;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author selcuk
 */
public class DeviceGroupDetailView extends AtofBaseDialog implements
        AbstractViewPanel, Validatable {

    private DeviceGroupDetailController m_controller;
    private boolean m_editMode;
    private int m_detailId;
    private DeviceGroupDetailRefined m_refined;

    /** Creates new form DeviceGroupDetailView */
    public DeviceGroupDetailView(Frame owner, boolean modal, boolean editMode) {
        super(owner, modal);
        m_controller = TestBedControllerList.newInstance().getDeviceGroupDetailController();
        m_editMode = editMode;
        initComponents();
        setFrameIcon("images/testbed/" + DeviceGroupDetailRefined.TYPE_NAME.toLowerCase(
                Locale.ENGLISH) + ".png");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        groupComboBox = new javax.swing.JComboBox();
        pcComboBox = new javax.swing.JComboBox();
        macTextField = new javax.swing.JTextField();
        ipTextField = new javax.swing.JTextField();
        portTextField = new javax.swing.JTextField();
        remoteComboBox = new javax.swing.JComboBox();
        nameTextField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        osComboBox = new javax.swing.JComboBox();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(getWindowTitle());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jLabel1.setText("Group");

        jLabel2.setText("Pc");

        jLabel3.setText("MacAddress ");

        jLabel4.setText("Ip");

        jLabel5.setText("Port");

        jLabel7.setText("Remote");

        jLabel8.setText("Name");

        populateGroupComboBox();

        populatePcComboBox();

        portTextField.setText("1");
        portTextField.setEnabled(false);

        remoteComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "false", "true" }));
        remoteComboBox.setSelectedIndex(1);
        remoteComboBox.setEnabled(false);

        jLabel6.setText("OS");

        populateOsComboBox();

        saveButton.setText("Save");
        setDefaultButton(saveButton);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel8))
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(remoteComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 283, Short.MAX_VALUE)
                            .addComponent(osComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 283, Short.MAX_VALUE)
                            .addComponent(groupComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 283, Short.MAX_VALUE)
                            .addComponent(pcComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 283, Short.MAX_VALUE)
                            .addComponent(portTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                            .addComponent(ipTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                            .addComponent(macTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                            .addComponent(nameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addGap(6, 6, 6)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, saveButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pcComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(macTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ipTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(osComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(remoteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (!validateForm()) {
            return;
        }
        saveButton.setEnabled(false);

        int deviceGroupId = getSelectedDeviceGroupId();
        int testPcId = getSelectedTestPcId();
        int osId = getSelectedOsId();
        String name = nameTextField.getText();
        String mac = macTextField.getText();
        String ip = ipTextField.getText();
        int port = Integer.parseInt(portTextField.getText());
        boolean isRemote = true;
        if (remoteComboBox.getSelectedIndex() == 0) {
            isRemote = false;
        }
        if (m_editMode) {
            HashMap values = new HashMap();
            values.put("detailId", m_detailId);
            values.put("name", name);
            values.put("ip", ip);
            values.put("mac", mac);
            values.put("isRemote", isRemote);
            values.put("port", port);
            values.put("groupId", deviceGroupId);
            values.put("pcId", testPcId);
            values.put("osId", osId);
            m_controller.operationSaveDetail(m_refined, values);
        } else {
            m_controller.operationAddDetail(name, ip, mac, isRemote, port,
                    deviceGroupId,
                    testPcId, osId);
        }

        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        WindowListener[] listeners = getWindowListeners();
        for (int i = 0; i < listeners.length; i++) {
            this.removeWindowListener(listeners[i]);
        }
        this.setVisible(false);
        this.setEnabled(false);
        m_controller.operationCloseWindow();
        this.dispose();
    }//GEN-LAST:event_formWindowClosed

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                DeviceGroupDetailController.VISIBLE_PROPERTY)) {
            this.centerParent();
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.DETAIL_REFINED_PROPERTY)) {
            DeviceGroupDetailRefined val = (DeviceGroupDetailRefined) evt.getNewValue();
            m_refined = val;
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.DETAIL_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            m_detailId = val;
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.GROUPID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectDeviceGroupCombobox(val);
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.PCID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectPcCombobox(val);
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.OSID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectOsCombobox(val);
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.MACADDRESS_PROPERTY)) {
            macTextField.setText((String) evt.getNewValue());
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.IP_PROPERTY)) {
            ipTextField.setText((String) evt.getNewValue());
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.PORT_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            portTextField.setText(val.toString());
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.ISREMOTE_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            remoteComboBox.setSelectedIndex(val);
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.NAME_PROPERTY)) {
            String val = (String) evt.getNewValue();
            nameTextField.setText(val);
        } else if (evt.getPropertyName().equals(
                DeviceGroupDetailController.ERROR_PROPERTY)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    public boolean validateForm() {
        boolean valid = true;
        StringBuilder builder = new StringBuilder();

        // check MAC address is valid
        if (AtofValidationUtils.isValidMacAddress(macTextField.getText()) == false) {
            builder.append("Invalid MAC address entered.\n");
            valid = false;
        }

        // check IP address is valid
        if (/*!ipTextField.getText().isEmpty() &&*/!AtofValidationUtils.isValidIpAddress(
                ipTextField.getText())) {
            builder.append("Invalid IP address entered.\n");
            valid = false;
        }

        // check port number is valid
        if (!ValidationUtils.isNumeric(portTextField.getText())) {
            builder.append("Invalid port number entered.\n");
            valid = false;
        }

        // check name
        if (ValidationUtils.isEmpty(nameTextField.getText())) {
            builder.append("Name must not be empty.\n");
            valid = false;
        }

        if (!valid) {
            JOptionPane.showMessageDialog(null,
                    builder.toString(),
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        return valid;
    }

    private void populateGroupComboBox() {
        groupComboBox.removeAllItems();
        List<DeviceGroupRefined> li = DeviceGroupFactory.newInstance().getDeviceGroupList();
        for (Iterator<DeviceGroupRefined> it = li.iterator(); it.hasNext();) {
            groupComboBox.addItem(it.next());
        }
    }

    private void populatePcComboBox() {
        pcComboBox.removeAllItems();
        List<TestPcRefined> li = TestPcFactory.newInstance().getTestPcList();
        for (Iterator<TestPcRefined> it = li.iterator(); it.hasNext();) {
            pcComboBox.addItem(it.next());
        }
    }

    private void populateOsComboBox() {
        osComboBox.removeAllItems();
        List<OperatingSystemRefined> li = OperatingSystemFactory.newInstance().getOperatingSystemList();
        for (Iterator<OperatingSystemRefined> it = li.iterator(); it.hasNext();) {
            osComboBox.addItem(it.next());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox groupComboBox;
    private javax.swing.JTextField ipTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField macTextField;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JComboBox osComboBox;
    private javax.swing.JComboBox pcComboBox;
    private javax.swing.JTextField portTextField;
    private javax.swing.JComboBox remoteComboBox;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables

    private void selectDeviceGroupCombobox(int id) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) groupComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            DeviceGroupRefined obj = (DeviceGroupRefined) model.getElementAt(i);
            if (obj != null && obj.getId() == id) {
                groupComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private DeviceGroupRefined getSelectedDeviceGroup() {
        return (DeviceGroupRefined) groupComboBox.getSelectedItem();
    }

    private int getSelectedDeviceGroupId() {
        int result = 0;
        DeviceGroupRefined obj = getSelectedDeviceGroup();
        if (obj != null) {
            result = obj.getId();
        }
        return result;
    }

    private void selectPcCombobox(int id) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) pcComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            TestPcRefined obj = (TestPcRefined) model.getElementAt(i);
            if (obj != null && obj.getId() == id) {
                pcComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private int getSelectedTestPcId() {
        int result = 0;
        TestPcRefined obj = (TestPcRefined) pcComboBox.getSelectedItem();
        if (obj != null) {
            result = obj.getId();
        }
        return result;
    }

    private void selectOsCombobox(int id) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) osComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            OperatingSystemRefined obj = (OperatingSystemRefined) model.getElementAt(
                    i);
            if (obj != null && obj.getId() == id) {
                osComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private int getSelectedOsId() {
        int result = 0;
        OperatingSystemRefined obj = (OperatingSystemRefined) osComboBox.getSelectedItem();
        if (obj != null) {
            result = obj.getId();
        }
        return result;
    }

    private String getWindowTitle() {
        if (m_editMode) {
            return new String("Edit Device Group Detail");
        } else {
            return new String("Add New Device Group Detail");
        }
    }
}
